import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import TextArea from '@/components/TextArea';
import { useAppDispatch, useAppSelector } from '@/store';
import { getUserAction, updatePhotoAction, updateUserAction } from '@/store/action/user';
import { UserType } from '@/store/reducer/user';
import { removeAuth } from '@/utils/storage';
import { DatePicker, Dialog, List, Popup, Toast } from 'antd-mobile';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { useHistory } from 'react-router-dom';
import styles from './index.module.scss';

type EditType = 'photo' | 'gender' | 'name' | 'intro';

export default function ProfileEdit() {
  const history = useHistory();
  const [visible, setVisible] = useState(false);
  const [rightVisible, setRightVisible] = useState(false);
  const [editType, setEditType] = useState('' as EditType);
  const [name, setName] = useState('');
  const [intro, setIntro] = useState('');

  const [birthVisible, setBirthVisible] = useState(false);

  const { user } = useAppSelector((state) => state.user);

  useEffect(() => {
    setName(user.name);
    setIntro(user.intro || '');
  }, [user]);

  const dispatch = useAppDispatch();
  const iptRef = useRef<HTMLInputElement>(null);

  const handleClickInput = () => {
    iptRef.current?.click();
  };

  const handleChange = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const formData = new FormData();
    if (e.target.files) {
      formData.append('photo', e.target.files[0]);
      await dispatch(updatePhotoAction(formData));
      handleRefresh();
    }
  };

  const handleRefresh = async () => {
    Toast.show({ content: '更新成功', icon: 'success' });
    await dispatch(getUserAction());
    setVisible(false);
    setRightVisible(false);
    setBirthVisible(false);
  };

  const handleShowEdit = (type: EditType) => {
    setEditType(type);
    if (type === 'name' || type === 'intro') setRightVisible(true);
    if (type === 'gender' || type === 'photo') setVisible(true);
  };

  const handleUpdateProfile = async (data: Partial<UserType>) => {
    await dispatch(updateUserAction(data));
    handleRefresh();
  };

  const handleCancel = () => {
    setRightVisible(false);
    setName(user.name);
    setIntro(user.intro || '');
  };

  const renderPohotOrGender = () => {
    if (editType === 'photo') {
      return (
        <>
          <div className="list-item" onClick={handleClickInput}>
            拍照
          </div>
          <div className="list-item" onClick={handleClickInput}>
            本地选择
          </div>
          <div className="list-item" onClick={() => setVisible(false)}>
            取消
          </div>
        </>
      );
    }

    if (editType === 'gender') {
      return (
        <>
          <div className="list-item" onClick={() => handleUpdateProfile({ gender: 0 })}>
            男
          </div>
          <div className="list-item" onClick={() => handleUpdateProfile({ gender: 1 })}>
            女
          </div>
          <div className="list-item" onClick={() => setVisible(false)}>
            取消
          </div>
        </>
      );
    }
  };

  const renderNameOrIntro = () => {
    const obj = {} as Partial<UserType>;
    if (editType === 'name') {
      obj.name = name;
    }

    if (editType === 'intro') {
      obj.intro = intro;
    }

    return (
      <>
        <NavBar
          right={
            <span onClick={() => handleUpdateProfile(obj)} className="submit-btn">
              提交
            </span>
          }
          onBack={handleCancel}
        >
          编辑{editType === 'name' ? '昵称' : '简介'}
        </NavBar>
        <div className="edit-content">
          {editType === 'name' && (
            <Input
              autoFocus
              value={name}
              onChange={(e) => setName(e.target.value)}
              className="edit-input"
            />
          )}
          {editType === 'intro' && (
            <TextArea
              autoFocus
              value={intro}
              onChange={(e) => setIntro(e.target.value)}
              className="edit-input"
            />
          )}
        </div>
      </>
    );
  };

  const handleLoginOut = () => {
    Dialog.confirm({
      title: '温馨提示',
      content: '你确定要退出吗',
      onConfirm: () => {
        removeAuth();
        history.push('/login');
        Toast.show({ content: '退出登录成功' });
      },
    });
  };

  useEffect(() => {
    dispatch(getUserAction());
  }, [dispatch]);
  return (
    <div className={styles.root}>
      <div className="content">
        <NavBar>个人资料</NavBar>
        <div className="wrapper">
          <List className="profile-list">
            <List.Item
              onClick={() => handleShowEdit('photo')}
              arrow
              extra={<img className="avatar" src={user.photo} alt="" />}
            >
              头像
            </List.Item>

            <List.Item onClick={() => handleShowEdit('name')} arrow extra={user.name}>
              昵称
            </List.Item>

            <List.Item
              onClick={() => handleShowEdit('intro')}
              arrow
              extra={<span className="intro">{user.intro}</span>}
            >
              简介
            </List.Item>

            <List.Item
              onClick={() => handleShowEdit('gender')}
              arrow
              extra={user.gender ? '女' : '男'}
            >
              性别
            </List.Item>
            <List.Item arrow extra={user.birthday} onClick={() => setBirthVisible(true)}>
              生日
            </List.Item>
          </List>

          <input onChange={handleChange} ref={iptRef} className="avatar-upload" type="file" />
        </div>

        <div className="logout">
          <button className="btn" onClick={handleLoginOut}>
            退出登录
          </button>
        </div>
      </div>
      <Popup visible={visible} className="popup-bottom-list" onMaskClick={() => setVisible(false)}>
        {renderPohotOrGender()}
      </Popup>

      <Popup
        bodyClassName="popup-right"
        onMaskClick={() => setRightVisible(false)}
        position="right"
        visible={rightVisible}
        destroyOnClose
      >
        {renderNameOrIntro()}
      </Popup>
      <DatePicker
        title="选择生日"
        visible={birthVisible}
        min={new Date('1922-01-01')}
        max={new Date()}
        value={new Date(user.birthday)}
        onCancel={() => setBirthVisible(false)}
        onConfirm={(value) => {
          console.log('dayjs  ----->  ', dayjs(value).format('YYYY-MM-DD'));
          handleUpdateProfile({ birthday: dayjs(value).format('YYYY-MM-DD') });
        }}
      ></DatePicker>
    </div>
  );
}
